package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public JsonData login(@RequestBody User user, HttpSession session){
        if(Objects.isNull(user)){
            return JsonData.buildError("表单信息有误");
        }
        User selectUser = userService.getOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getUsername, user.getUsername())
                        .eq(User::getPassword, user.getPassword()));
        if(selectUser==null){
            // 也有可能是未注册
            return JsonData.buildError("账号或密码错误");
        }
        session.setAttribute("flag",true);
        return JsonData.buildSuccess();
    }

    @GetMapping("/logout")
    public JsonData logout(HttpSession session){
        session.setAttribute("flag",false);
        System.out.println("退出登录成功");
        return JsonData.buildSuccess();
    }
}
